package com.wtwd.campus.receiver;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.h5_manager.entity.DeviceLog;
import com.wtwd.campus.h5_manager.service.DeviceLogService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.service.WarningRecordService;
import com.wtwd.campus.utils.GPSUtils;
import com.wtwd.campus.utils.PushUtils;
import com.wtwd.campus.utils.ReceiverUtils;
import com.wtwd.campus.utils.Vizhi.VizhiService;
import com.wtwd.campus.utils.Vizhi.entity.Address;
import com.wtwd.campus.utils.Vizhi.entity.Point;
import com.wtwd.campus.utils.Vizhi.entity.Position;
import com.wtwd.campus.utils.Vizhi.entity.vo.VizhiVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@MsgType(value = Constants.ACTIVE_DEVICE_LOCATION)
public class ReceiverLocationDataHandler implements IReceiverHandler {
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private ReceiverUtils receiverUtils;
    @Autowired
    private WarningRecordService warningRecordService;
    @Autowired
    private PushUtils pushUtils;
    @Autowired
    private DeviceLogService deviceLogService;

    @Resource
    private VizhiService vizhiService;


    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqDeviceUpLocation mqDeviceUpLocation = (MqDeviceUpLocation) mqMessage.getObject();
        String imei = mqDeviceUpLocation.getImei();
        String commandNumber = mqDeviceUpLocation.getCommandNumber();
        //处理指令回复的时间
        String deviceDate = mqDeviceUpLocation.getDeviceDate();
        String deviceTime = mqDeviceUpLocation.getDeviceTime();
        Long time = getTime(deviceDate, deviceTime);
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        LocationDataVo locationDataVo = null;
        if (deviceInfo != null) {
            if (mqDeviceUpLocation.getMqLocationData().getLatitude() != 0 && mqDeviceUpLocation.getMqLocationData().getLongitude() != 0) {
                //进行定位数据存储以及围栏告警记录的存储
                deviceInfo = receiverUtils.dealLocation(mqDeviceUpLocation.getMqLocationData(), time, deviceInfo, 4);
                locationDataVo = new LocationDataVo();
                locationDataVo.setLocationType(1);
                locationDataVo.setLatitude(mqDeviceUpLocation.getMqLocationData().getLatitude().toString());
                locationDataVo.setLongitude(mqDeviceUpLocation.getMqLocationData().getLongitude().toString());
                locationDataVo.setAddress(deviceInfo.getAddress());
                locationDataVo.setImei(imei);
                locationDataVo.setLocationTime(time);
            } else {
                //用基站信息获取位置
                String lbsInfo = mqDeviceUpLocation.getLbsInfo();
                if (!StringUtils.isBlank(lbsInfo)) {
                    String[] split = lbsInfo.split(",");
                    if (!split[0].equals("0")) {
                        try {
                            MqLocationData mqLocationData = new MqLocationData();
                            VizhiVo wifiAddress = vizhiService.intelligentHardwareLocation(imei, null,lbsInfo);
                            if (wifiAddress==null){
                                return;
                            }
                            Address address = wifiAddress.getLocation().getAddress();
                            if (address!=null&& StringUtils.isNotBlank(address.getName())){
                                mqLocationData.setAddress(address.getName());
                            }
                            Position position = wifiAddress.getLocation().getPosition();
                            Point point = position.getPoint();
                            double[] locationItem = GPSUtils.gcj02_To_Gps84(point.getLatitude(), point.getLongitude());
                            mqLocationData.setLatitude(locationItem[0]);
                            mqLocationData.setLongitude(locationItem[1]);
                            receiverUtils.dealLocation(mqLocationData, time, deviceInfo, 5);
//                            JSONObject lbsAddress = GaoDeUtil.getLbsAddress(lbsInfo.split("\\|")[0],
//                                    lbsInfo.replaceAll(lbsInfo.split("\\|")[0].concat("|"), ""), imei);
//                            String type = lbsAddress.getJSONObject("result").getString("type");
//                            if (Integer.parseInt(type) > 0) {
//                                String location = lbsAddress.getJSONObject("result").getString("location");
//                                String lat = location.split(",")[1];
//                                String lgn = location.split(",")[0];
//                                double[] locationItem = GPSUtils.gcj02_To_Gps84(Double.parseDouble(lat), Double.parseDouble(lgn));
//                                MqLocationData mqLocationData = new MqLocationData();
//                                mqLocationData.setLatitude(locationItem[0]);
//                                mqLocationData.setLongitude(locationItem[1]);
//                                receiverUtils.dealLocation(mqLocationData, time, deviceInfo, 5);
//                            }
                        } catch (Exception e) {
                            logger.error("基站转经纬度错误，或保存定位错误");
                        }
                    }
                }
            }
            //若电量不足则存储低电量告警
            Integer battery = mqDeviceUpLocation.getBattery();
//            if (battery < 20) {
//                //存储低电量告警
//                WarningRecord record = new WarningRecord();
//                record.setDevice_id(deviceInfo.getDeviceId());
//                record.setAddress(deviceInfo.getAddress());
//                record.setWarning_time(time);
//                record.setWarning_type(Constants.LOW_BATTERY_WARNING_TYPE);
//                warningRecordService.addWarningRecord(record);
//            }
            //修改设备信息
            deviceInfo.setLastUpTime(System.currentTimeMillis());
            deviceInfo.setBattery(battery);
            deviceInfoService.modifyDeviceInfo(deviceInfo);
            //删除缓存中的指令
            String delKey = Constants.ACTIVE_DEVICE_LOCATION.concat("-").concat(commandNumber);
            receiverUtils.deleteCommandInRedis(imei, delKey);
            //完善指令下发记录
            receiverUtils.completeCommandRecord(Constants.ACTIVE_DEVICE_LOCATION, imei, commandNumber, null, Constants.COMMAND_COMPLETE, time);
            //存储设备接收日志
            DeviceLog deviceLog = new DeviceLog();
            deviceLog.setCommandNumber(commandNumber);
            deviceLog.setSendUser(Constants.DEVICE_USER);
            deviceLog.setImei(imei);
            deviceLog.setBigType(Constants.MESS_TYPE);
            deviceLog.setType(Constants.ACTIVE_DEVICE_LOCATION);
            JSONObject text = new JSONObject();
            text.put("设备号", imei);
            text.put("经度", mqDeviceUpLocation.getMqLocationData().getLongitude());
            text.put("纬度", mqDeviceUpLocation.getMqLocationData().getLatitude());
            text.put("lbs信息(基站信息)", mqDeviceUpLocation.getLbsInfo());
            text.put("电量", mqDeviceUpLocation.getBattery());
            text.put("设备日期", deviceDate);
            text.put("设备时间", time);
            text.put("电量", battery);
            text.put("设备状态", mqDeviceUpLocation.getDeviceStatus());
            deviceLog.setCmd(text.toJSONString());
            deviceLog.setSendTime(System.currentTimeMillis());
            deviceLog.setState(1);
            deviceLogService.addDeviceLog(deviceLog);
        } else {
            saveUnInStorage(imei);
            receiverUtils.cloaseChannel(imei);
        }
    }
}
